package com.zhangdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhangdp.dto.Result;
import com.zhangdp.entity.Shop;
import com.zhangdp.mapper.ShopMapper;
import com.zhangdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.zhangdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        // 1. 缓存穿透  缓存穿透是指客户端请求的数据在缓存中和数据库中都不存在，这样缓存永远不会生效，这些请求都会打到数据库。 有缓存击穿的问题
        // Shop shop = this.queryWithPassThrough(id);
        // 2. 解决缓存击穿 缓存击穿问题也叫热点Key问题，就是一个被高并发访问并且缓存重建业务较复杂的key突然失效了，无数的请求访问会在瞬间给数据库带来巨大的冲击

        // 2.1 互斥锁解决
        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("查询失败");
        }
        return Result.ok(shop);
    }

    /**
     * 互斥锁 解决 缓存击穿问题
     * @param id 商家id
     * @return 商家信息
     */
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String resultJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(resultJson)) {
            return JSONUtil.toBean(resultJson, Shop.class);
        }
        if ("".equals(resultJson)) {
            return null;
        }
        // 未命中 获取互斥锁
        // 判断是否获取成功
        Shop shop;
        try {
            boolean isLock = tryLock(id);
            if (!isLock) {
                // 失败就休眠
                Thread.sleep(100);
                // 在尝试获取数据
                return queryWithMutex(id);
            }
            // 获取锁成功 再次判断是否有缓存 有则不需要创建
            resultJson = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotEmpty(resultJson)) {
                return JSONUtil.toBean(resultJson, Shop.class);
            }
            if ("".equals(resultJson)) {
                return null;
            }

            // 成功就创建缓存
            shop = this.getById(id);
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放互斥锁
            unlock(id);
        }
        return shop;
    }


    /**
     * 查询店铺 解决缓存穿透
     *
     * @param id 店铺id
     * @return 店铺
     */
    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String resultJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(resultJson)) {
            return JSONUtil.toBean(resultJson, Shop.class);
        }
        if ("".equals(resultJson)) {
            return null;
        }
        Shop shop = this.getById(id);
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }


    /**
     * 尝试获取锁
     *
     * @param id 想要获取锁的id
     * @return 是否获取到锁
     */
    private boolean tryLock(Long id) {
        String key = LOCK_SHOP_KEY + id;
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS));
    }

    /**
     * 释放锁
     *
     * @param id 要释放锁的id
     */
    private void unlock(Long id) {
        String key = LOCK_SHOP_KEY + id;
        stringRedisTemplate.delete(key);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    /**
     * 查询店铺 利用逻辑过期解决缓存击穿
     *
     * @param id 店铺id
     * @return 店铺
     */
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1.先去缓存中查询
        String resultJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 如果缓存中无数据 直接返回空
        if (StrUtil.isBlank(resultJson)) {
            return null;
        }
        // 3. 有数据 判断是否过期
        RedisData redisData = JSONUtil.toBean(resultJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 4. 判断过期时间
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 5. 未过期 直接返回
            return shop;
        }
        // 6. 过期了 缓存重建
        if (tryLock(id)) {
            // 获取锁成功后再次判断时候过期
            resultJson = stringRedisTemplate.opsForValue().get(key);
            // 7. 如果缓存中无数据 直接返回空
            if (StrUtil.isBlank(resultJson)) {
                return null;
            }
            // 8. 有数据 判断是否过期
            redisData = JSONUtil.toBean(resultJson, RedisData.class);
            shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
            expireTime = redisData.getExpireTime();
            // 9. 判断过期时间
            if (expireTime.isAfter(LocalDateTime.now())) {
                // 10. 未过期 直接返回
                return shop;
            }
            // 11. 过期 开启独立线程 实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveShop2Redis(id, CACHE_SHOP_TTL);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(id);
                }
            });
        }
        return shop;
    }

    public void saveShop2Redis(Long id, Long expireTime) {
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData), expireTime, TimeUnit.SECONDS);
    }


    @Override
    @Transactional
    public Result update(Shop shop) {
        if (updateById(shop)) {
            stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
            return Result.ok();
        }
        return Result.fail("修改失败!");
    }
}
